package cn.xuqiudong.rpc.protocol.netty.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.xuqiudong.rpc.extension.XqdExtensionFactory;
import cn.xuqiudong.rpc.protocol.netty.model.NettyHeader;
import cn.xuqiudong.rpc.protocol.netty.model.NettyProtocolData;
import cn.xuqiudong.rpc.serializer.XqdSerializer;

/**
 * 描述: netty 中使用的编码器
 * @author Vic.xu
 * @date 2022-02-18 11:17
 *
 */
public class XqdEncoder extends MessageToByteEncoder<NettyProtocolData<Object>> {

    /**
     * 通过SpiXqdExtension 获取自适应的序列化方式
     */
    private static XqdSerializer serializer = XqdExtensionFactory.defaultExtendFactory().getAdaptiveXqdExtension(XqdSerializer.class);

    private static Logger logger = LoggerFactory.getLogger(XqdEncoder.class);

    @Override
    protected void encode(ChannelHandlerContext ctx, NettyProtocolData<Object> msg, ByteBuf out) throws Exception {
        logger.debug("into XqdEncoder");
        NettyHeader header=msg.getHeader();
        /**
         * 参照  {@link NettyHeader}  的定义 逐一写入
         */
        out.writeShort(header.getMagic());
        out.writeByte(header.getSerialType());
        out.writeByte(header.getRequestType());
        out.writeLong(header.getRequestId());

        Object body = msg.getBody();
        //序列化body
        byte[] data = serializer.serialize(body);
        header.setLength(data.length);
        out.writeInt(data.length);
        out.writeBytes(data);
    }
}
